package com.tinyengine.it.controller.engine.extend;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tinyengine.it.common.base.PageQueryVo;
import com.tinyengine.it.common.base.Result;
import com.tinyengine.it.model.entity.TApp;
import com.tinyengine.it.service.engine.extend.TAppService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Tag(name = "app应用", description = "TappController")
@RestController
@RequiredArgsConstructor
@RequestMapping("/app-center/api/extend/app")
public class TappController {

    private final TAppService tAppService;

    @Operation(summary = "保存or更新")
    @PostMapping("/saveUpdate")
    public Result saveUpdate(@RequestBody @Valid TApp app) {

        TApp tApp = tAppService.getOne(new LambdaQueryWrapper<TApp>().eq(TApp::getName, app.getName()).last("limit 1"));
        if (ObjUtil.isNull(app.getId()) && ObjUtil.isNotNull(tApp)) {
            return Result.failed("该应用名称已经存在!");
        }
        tAppService.saveOrUpdate(app);
        return Result.success(app);
    }

    @Parameter(name = "id", description = "id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "删除", method = "POST")
    @PostMapping("/delete/{id}")
    public Result delete(@Valid @PathVariable Integer id) {

        tAppService.removeById(id);

        return Result.success();
    }

    @Operation(summary = "获取分页列表")
    @PostMapping("/pages/list")
    public Result<IPage<TApp>> getPageList(@RequestBody PageQueryVo pageQueryVo) {
        IPage<TApp> page = tAppService.page(
                new Page<>(
                        pageQueryVo.getCurrent(),
                        pageQueryVo.getPageSize()
                )
        );
        return Result.success(page);
    }
}
